<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Family;
use App\Models\Project;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\TeamCategory;
use App\Models\TeamServiceObj;
use App\Models\User;
use App\Models\UserCollection;
use App\Models\UserMessage;
use App\Models\UserTeam;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use App\Models\WechatTempMsg;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;
use anlutro\LaravelSettings\Facade AS Setting;

class TeamController extends Controller
{

    public function listInfo(Request $request)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        $name = $request->input('name');
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $nodes = Team::query();
        $nodes = $nodes->where('verify_status', 1)->where('in_blacklist', 0)->where('org_id', $this->getOrdId());
        if(($cityCode = $this->getCityCode()))
        {
            $nodes = $nodes->where('city_id', $cityCode);
        }

        if($request->has('service_object') && !empty($serviceObject= $request->input('service_object')))
        {
            $serviceObject = is_array($serviceObject)? $serviceObject:explode(',', $serviceObject);
            $objCount = count($serviceObject);
            $tids = TeamServiceObj::where('org_id', $this->getOrdId())->whereIn('service_object_name', $serviceObject)->groupBy('team_id')->havingRaw("count(*) ={$objCount}")->get(['team_id'])->toArray();

            $ids = array_map(function($node){
                return $node['team_id'];
            }, $tids);

            $nodes->whereIn('id', $ids);
        }

        if($request->has('service_category') && !empty($serviceCategory= $request->input('service_category')))
        {
            $serviceCategory = is_array($serviceCategory)? $serviceCategory:explode(',', $serviceCategory);
            $cateCount = count($serviceCategory);
            $tids = TeamCategory::where('org_id', $this->getOrdId())->whereIn('service_category_name', $serviceCategory)->groupBy('team_id')->havingRaw("count(*) ={$cateCount}")->get(['team_id'])->toArray();

            $ids = array_map(function($node){
                return $node['team_id'];
            }, $tids);
            $nodes->whereIn('id', $ids);
        }

        if($request->has('team_type'))
        {
            $nodes = $nodes->where('type', $request->input('team_type'));
        }

        if($request->has('county_id'))
        {
            $nodes = $nodes->where('county_id', $request->input('county_id'));
        }

        if(!empty($name))
        {
            $nodes->where('name', 'like', "%{$name}%");
        }
        $count = $nodes->count();
        $nodes = $nodes->orderBy('id','desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $list = [];
        foreach($lists as $msg)
        {
            $tmp = Team::format($msg);
            $list[] = $tmp;
        }

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }

    public function info(Request $request, $id)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        $node = Team::query();
        $node = $node->where('org_id', $this->getOrdId())->where('id', $id);
        $node = $node->first();

        if($node->verify_status != 1)
        {
            $this->setStatus(10002);
            $this->setMsg('该团队审核状态不为通过,无法查看');
            return $this->response();
        }
        if($node->in_blacklist != 0)
        {
            $this->setStatus(10002);
            $this->setMsg('该团队已被管理员拉黑,无法查看');
            return $this->response();
        }

        $data = $node->getAllInfo();

        $data['parent'] = Team::format(Team::where('id', $node->parent_id)->first());
        $userTeam = UserTeam::where('team_id', $id)->where('user_id', $userInfo->id)->first();
        $data['join_status'] = empty($userTeam)? -1:$userTeam->verify_status;
        $userCollection = UserCollection::where('type', 1)->where('relation_id', $id)->where('user_id', $userInfo->id)->first();
        $data['collection_status'] = empty($userCollection)? 0:1;

        $this->setData($data);
        return $this->response();
    }

    public function  join(Request $request, $id)
    {
        $rules = ['type'=>'required|in:0,1'];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }
        $type = $request->input('type');
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        if($userInfo->volunteer->in_blacklist == 1)
        {
            $this->setStatus(10001);
            $this->setMsg('您被拉入黑名单，无法加入团队');
            return $this->response();
        }

        $node = Team::query();
        $node = $node->where('org_id', $this->getOrdId())->where('id', $id);
        $node = $node->first();


        if($node->verify_status != 1)
        {
            $this->setStatus(10002);
            $this->setMsg('该团队审核状态不为通过,无法查看');
            return $this->response();
        }
        if($node->in_blacklist != 0)
        {
            $this->setStatus(10002);
            $this->setMsg('该团队已被管理员拉黑,无法查看');
            return $this->response();
        }

        if($type == 1 && $node->join_type == 3)
        {
            $this->setStatus(10002);
            $this->setMsg('该团队禁止加入');
            return $this->response();
        }



        switch($type)
        {
            //退出
            case 0:
                $userTeam = UserTeam::where('user_id', $userInfo->id)->where('team_id', $id)->first();
                if(empty($userTeam))
                {
                    $this->setStatus(10001);
                    $this->setMsg('您还未加入该团队,无法退出');
                    return $this->response();
                }else{
                    if($userTeam->verify_status != 1)
                    {
                        $this->setStatus(10001);
                        $this->setMsg('您还未加入该团队,无法退出');
                        return $this->response();
                    }
                    $userTeam->delete();
                    $count = UserTeam::where('team_id', $node->id)->where('verify_status', 1)->count();
                    $node->fill(['team_size'=>$count])->save();
                    return $this->response();
                }
                break;

            //加入
            case 1:
                $userTeam = UserTeam::where('user_id', $userInfo->id)->where('team_id', $id)->first();
                if(empty($userTeam))//加入
                {
                    $userTeam = new UserTeam();
                    $data['user_id'] = $userInfo->id;
                    $data['team_id'] = $id;
                    $data['verify_status'] = $node->join_type == 1? 1:0;
                    $data['verify_msg'] = $node->join_type == 1? '团队免审,自动通过':'';
                    try{
                        if($userTeam->fill($data)->save())
                        {
                            if($data['verify_status'] == 1)
                            {
                                //微信模版消息，用户加入团队收到审核通过
                                WechatTempMsg::add(3, ['user_id'=>$userInfo->id, 'team_id'=>$id, 'user_team_id'=>$userTeam->id]);

                                $count = UserTeam::where('team_id', $node->id)->where('verify_status', 1)->count();
                                $node->fill(['team_size'=>$count])->save();
                            }

                            //微信模版消息，团队管理员收到用户申请加入团队
                            WechatTempMsg::add(56, ['user_id'=>$userInfo->id, 'team_id'=>$id, 'user_team_id'=>$userTeam->id]);
                            return $this->response();
                        }
                    }catch (\Exception $e)
                    {
                        $this->setStatus(-10001);
                        $this->setMsg('系统忙，请重试');
                        return $this->response();
                    }

                }else{
                    $this->setStatus(10001);
                    if($userTeam->verify_status == 0)
                    {
                        $this->setMsg('已申请加入,请耐心等待团队管理员审核');
                    }elseif($userTeam->verify_status == 1){
                        $this->setMsg('您已时该团队成员,请不要重复申请');
                    }elseif($userTeam->verify_status == 2)
                    {
                        $this->setMsg('您的申请被团队管理员驳回,请勿重复申请');
                    }

                    return $this->response();
                }
                break;
        }

    }

}
